package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.utils.uuUtils;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.Order;
import com.hemaapp.yjnh.bean.Order.BillChild;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.ImageUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomToastUtil;

/**
 * 买家普通订单详情
 *
 * @author GuiyouZhang
 */
public class BuyerOrderDetailActivity extends BaseActivity implements OnClickListener {

    private final static int REQUEST_PAY = 0x01;//去自己支付
    private final static int REQUEST_FRIEND = 0x02;//朋友代付
    private final static int REQUEST_ORDER_COMMIT = 0x03;//评价订单
    private final static int REQUEST_ORDER_AFTERSALE = 0x04;//申请售后
    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.tv_client_name)
    TextView tvClientName;
    @Bind(R.id.tv_mobile)
    TextView tvMobile;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.tv_order_sn)
    TextView tvOrderSn;
    @Bind(R.id.layout_goods)
    LinearLayout layoutGoods;
    @Bind(R.id.tv_cash_stamp)
    TextView tvCashStamp;
    @Bind(R.id.tv_freight)
    TextView tvFreight;
    @Bind(R.id.tv_money)
    TextView tvMoney;
    @Bind(R.id.tv_order_num)
    TextView tvOrderNum;
    @Bind(R.id.tv_order_time)
    TextView tvOrderTime;
    @Bind(R.id.tv_express_name)
    TextView tvExpressName;
    @Bind(R.id.tv_express_num)
    TextView tvExpressNum;
    @Bind(R.id.tv_order_status)
    TextView tvOrderStatus;
    @Bind(R.id.tv_cancel)
    TextView tvCancel;
    @Bind(R.id.tv_confirm)
    TextView tvConfirm;
    @Bind(R.id.tv_friend_pay)
    TextView tvFriendPay;
    @Bind(R.id.tv_pay)
    TextView tvPay;
    @Bind(R.id.layout_bottom)
    LinearLayout layoutBottom;

    private Order mOrder;//当前的订单
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_buyer_order_detail);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        String orderId = mIntent.getStringExtra("order_id");
        getNetWorker().orderGet(user.getToken(), orderId);
    }

    @Override
    protected void setListener() {
        titleText.setText("订单详情");
        titleRightBtn.setVisibility(View.GONE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_PAY:
            case REQUEST_ORDER_COMMIT:
            case REQUEST_ORDER_AFTERSALE:
            case REQUEST_FRIEND:
                getNetWorker().orderGet(user.getToken(), mOrder.getId());
                break;
        }
    }

    private void setDatas(){
        //设置地址
        tvClientName.setText(mOrder.getConsignee());
        tvMobile.setText(mOrder.getPhone());
        tvAddress.setText(mOrder.getAddress());
        //订单信息
        double goodsFee = 0.0;
        double stampFee = 0.0;
        try {
            goodsFee = Double.parseDouble(mOrder.getGoods_fee());
            stampFee = Double.parseDouble(mOrder.getScore_fee());
        }catch (Exception e) {
            e.printStackTrace();
        }
        tvCashStamp.setText("¥"+ uuUtils.formatAfterDot2(goodsFee-stampFee+"")+" + ");
        BaseUtil.addStampSign(mContext, tvCashStamp, R.drawable.food_stamp_grey);
        tvCashStamp.append(mOrder.getScore_fee()+"粮票");
        tvFreight.setText("¥"+ mOrder.getShipping_fee());
        tvMoney.setText("¥"+mOrder.getTotal_fee());
        tvOrderSn.setText("订单号："+mOrder.getBill_sn());
        tvOrderNum.setText("订单号："+mOrder.getBill_sn());
        tvOrderTime.setText("下单时间："+mOrder.getRegdate());
        if (isNull(mOrder.getShipping_name()))
            tvExpressName.setText("快递公司：暂无信息");
        else
            tvExpressName.setText("快递公司："+BaseUtil.transNull(mOrder.getShipping_name()));
        if (isNull(mOrder.getShipping_num()))
            tvExpressNum.setText("快递单号：暂无信息");
        else
            tvExpressNum.setText("快递单号："+BaseUtil.transNull(mOrder.getShipping_num()));
        setOrderStatus();
        //动态添加多个商品
        if (layoutGoods.getChildCount() != 0) {
            layoutGoods.removeAllViews();
        }
        for (int i = 0; i < mOrder.getChildren().size(); i++) {
            BillChild child = mOrder.getChildren().get(i);
            View view = LayoutInflater.from(mContext).inflate(
                    R.layout.item_order_goods, null);
            ItemViewHolder ivHolder = new ItemViewHolder();
            itemFindView(view, ivHolder);
            setItem(i, child, view, ivHolder);
//            ivHolder.img.setTag(mOrder.getChildren().get(i));
//            ivHolder.img.setOnClickListener(new OnClickListener() {
//
//                @Override
//                public void onClick(View v) {
//                    BillChild child = (BillChild) v.getTag();
//                    // 先根据商品属性自己判断
//                    Intent intent = BaseUtil.createBlogIntent(mContext, child.getType());
//                    intent.putExtra("blog_id", child.getBlog_id());
//                    mContext.startActivity(intent);
//                }
//            });
            view.setTag(mOrder.getChildren().get(i));
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    BillChild child = (BillChild) v.getTag();
                    String itemtype = child.getItemtype();//状态	0正常 1申请中 2卖家同意等待买家发货 3拒绝 4退货中 5退货完成
                    if (!itemtype.equals("0")) {
                        Intent itAfter = new Intent(mContext, AfterSalesDetailActivity.class);
                        itAfter.putExtra("order_id", child.getId());
                        itAfter.putExtra("isSeller", false);
                        mContext.startActivityForResult(itAfter, REQUEST_ORDER_AFTERSALE);
                    }else {
                        // 先根据商品属性自己判断
                        Intent intent = BaseUtil.createBlogIntent(mContext, child.getType());
                        intent.putExtra("blog_id", child.getBlog_id());
                        mContext.startActivity(intent);
                    }
                }
            });
        }
    }

    /**
     * 获取订单的状态
     *订单状态逻辑：
     * 1、已关闭订单显示“已关闭”；
     * 2、再去判断订单中的退货商品，
     *      ①如果全部退货成功：订单状态：“问题订单”；底部按钮：无
     *      ②其他情况，包括：有的商品退货有的商品没退货，全部退货失败，继续按3的逻辑判断；
     * 3、根据订单的交易状态TradeType来判断：
     *      ①未付款：
     *          1)我自己的未付款订单：订单状态：未付款；底部按钮：取消订单、代付、支付
     *          2)别人请我帮忙代付的订单:不在这个界面
     *      ②待发货：订单状态：待发货；底部按钮：无
     *      ③待收货：订单状态：待收货；底部按钮：确认收货
     *      ④待评价：订单状态：待评价；底部按钮：无
     *      ⑤交易成功：订单状态：交易成功；底部按钮：无
     *
     * @return
     */
    private void setOrderStatus() {
        //订单状态	1：有效 2：已删除
        if (mOrder.getStatetype().equals("2")) {
            tvOrderStatus.setText("订单状态：已关闭");
            setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
        }
        if (mOrder.getReturnflag().equals("1")) {//有退货
            //状态:0正常;1申请中;2等待买家发货;3拒绝;4退货中;5退货完成
            //
            for (BillChild item : mOrder.getChildren()) {
                int returnSucCount = 0;
                //计算退货成功的商品数量
                if (item.getItemtype().equals("5")) {
                    returnSucCount++;
                }
                if (returnSucCount == mOrder.getChildren().size()) {//如果全部退货成功,那么就结束，否则按正常逻辑判断
                    tvOrderStatus.setText("订单状态：问题订单");
                    setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
                    return;
                }
            }
        }
        //交易状态	0 未付款 1: 已付款待发货 2 待收货 3 已收货待评价 4 已评价交易成功
        if (mOrder.getTradetype().equals("0")) {
            tvOrderStatus.setText("订单状态：待付款");
            setBottomButton(new int[]{View.VISIBLE, View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE});
        }else if (mOrder.getTradetype().equals("1")) {
            tvOrderStatus.setText("订单状态：待发货");
            setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
        }else if (mOrder.getTradetype().equals("2")) {
            tvOrderStatus.setText("订单状态：待收货");
            setBottomButton(new int[]{View.VISIBLE, View.GONE, View.VISIBLE, View.GONE, View.GONE});
        }else if (mOrder.getTradetype().equals("3")) {
            tvOrderStatus.setText("订单状态：待评价");
            setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
        }else if (mOrder.getTradetype().equals("4")) {
            tvOrderStatus.setText("订单状态：交易成功");
            setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE, View.GONE});
        }
    }

    /**
     * @param visibility
     * 底部按钮的顺序依次为：
     * layoutBottom、取消订单、确认收货、代付、支付
     */
    public void setBottomButton(int[] visibility) {
        layoutBottom.setVisibility(visibility[0]);
        if (visibility[0] == View.VISIBLE) {
            tvCancel.setVisibility(visibility[1]);
            tvConfirm.setVisibility(visibility[2]);
            tvFriendPay.setVisibility(visibility[3]);
            tvPay.setVisibility(visibility[4]);
        }
    }

    @OnClick({R.id.title_left_btn, R.id.tv_cancel, R.id.tv_confirm, R.id.tv_friend_pay, R.id.tv_pay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.tv_cancel:
                showAlertDialog("确认取消订单吗？", "确定", new HemaButtonDialog.OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        getNetWorker().orderSaveoperate(user.getToken(), mOrder.getId(), "1", "无",
                                    "无", "无", "无");
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
                break;
            case R.id.tv_confirm:
                showAlertDialog("一旦确认收货，交易自动完成", "确定", new HemaButtonDialog.OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        getNetWorker().orderSaveoperate(user.getToken(), mOrder.getId(), "2", "无",
                                "无", "无", "无");
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
                break;
            case R.id.tv_pay:
                Intent itPay = new Intent(mContext, PayActivity.class);
                itPay.putExtra("order", mOrder);
                startActivityForResult(itPay, REQUEST_PAY);
                break;
            case R.id.tv_friend_pay:
                StringBuffer name = new StringBuffer();
                for (BillChild item : mOrder.getChildren()) {
                    name.append(item.getName()).append("\r\n");
                }
                name.delete(name.length()-2, name.length());
                Intent itFriend = new Intent(mContext, FriendPayActivity.class);
                itFriend.putExtra("name", name.toString());
                itFriend.putExtra("fee", mOrder.getTotal_fee());
                itFriend.putExtra("info", user.getNickname() + "(" + user.getUsername() + ")");
                itFriend.putExtra("deal_here", true);
                itFriend.putExtra("order_id", mOrder.getId());
                startActivityForResult(itFriend, REQUEST_FRIEND);
                break;
        }
    }

    public void showAlertDialog(String title, String ok, HemaButtonDialog.OnButtonListener listener) {
        HemaButtonDialog dialog = new HemaButtonDialog(mContext);
        dialog.setText(title);
        dialog.setRightButtonText(ok);
        dialog.setButtonListener(listener);
        dialog.show();
    }

    private class ItemViewHolder {
        private ImageView img;
        private TextView name;
        private TextView price;
        private TextView amount;
        TextView tvCommit;
        TextView tvAfterSale;
        TextView tvHint;
        View div;
        private TextView tvGoodsSpec;
    }

    /**
     * 一个订单中的多个商品
     *
     * @param view
     * @param ivHolder
     */
    private void itemFindView(View view, ItemViewHolder ivHolder) {
        ivHolder.img = (ImageView) view.findViewById(R.id.img);
        ivHolder.name = (TextView) view.findViewById(R.id.good_name);
        ivHolder.price = (TextView) view.findViewById(R.id.price);
        ivHolder.amount = (TextView) view.findViewById(R.id.count);
        ivHolder.tvCommit = (TextView) view.findViewById(R.id.tv_commit);
        ivHolder.tvAfterSale = (TextView) view.findViewById(R.id.tv_aftersale);
        ivHolder.tvHint = (TextView) view.findViewById(R.id.tv_hint);
        ivHolder.div = view.findViewById(R.id.divider);
        ivHolder.tvGoodsSpec = (TextView) view.findViewById(R.id.tv_goods_spec);
    }

    private void setItem(int i, final BillChild child, View view, ItemViewHolder ivHolder) {
        ImageUtils.loadSmalImage(mContext, child.getImgurl(), ivHolder.img);
        ivHolder.name.setText(child.getName());
        ivHolder.price.setText("¥" + child.getPrice());
        ivHolder.amount.setText("x" + child.getBuycount());
        if (!TextUtils.isEmpty(child.getOne_specname())) {
            ivHolder.tvGoodsSpec.setVisibility(View.VISIBLE);
            StringBuffer spec = new StringBuffer(child.getOne_spec());
            spec.append(":").append(child.getOne_specname());
            if (!TextUtils.isEmpty(child.getTwo_specname())) {
                spec.append("    ").append(child.getTwo_spec()).append(":").append(child.getTwo_specname());
            }
            ivHolder.tvGoodsSpec.setText(spec.toString());
        }else
            ivHolder.tvGoodsSpec.setVisibility(View.GONE);

        if (i == mOrder.getChildren().size() - 1) {
            ivHolder.div.setVisibility(View.GONE);
        } else {
            ivHolder.div.setVisibility(View.VISIBLE);
        }
        //判断是否已经评价
        if (mOrder.getTradetype().equals("3")) {//如果订单未评价，那么再去判断订单中的商品有没有评价
            if (child.getReplytype().equals("0")) {//订单中的商品未评论，显示去评价
                ivHolder.tvCommit.setVisibility(View.VISIBLE);
            } else {
                ivHolder.tvCommit.setVisibility(View.GONE);
                ivHolder.tvHint.setVisibility(View.VISIBLE);
                ivHolder.tvHint.setText("已评价");
            }
        }
        //判断是否可以申请售后
        //TradeType:	0:未付款;1:已付款待发货;2:待收货;3:已收货待评价;4:已评价交易成功
        if (mOrder.getTradetype().equals("1") || mOrder.getTradetype().equals("2") || (mOrder.getTradetype().equals("3") && child.getReplytype().equals("0"))) {//订单已经收货后，订单中的商品就可以显示申请售后
            if (child.getBlogReturnflag().equals("0")) {//允许退货标记:0不允许;1允许
                ivHolder.tvAfterSale.setVisibility(View.GONE);
                ivHolder.tvHint.setVisibility(View.VISIBLE);
                ivHolder.tvHint.setText("不支持退货");
            } else {
                //判断商品的售后申请记录
                String itemtype = child.getItemtype();//状态	0正常 1申请中 2卖家同意等待买家发货 3拒绝 4退货中 5退货完成
                if (itemtype.equals("0")) {//正常情况显示申请售后
                    ivHolder.tvAfterSale.setVisibility(View.VISIBLE);
                }else if (itemtype.equals("1")) {
                    ivHolder.tvCommit.setVisibility(View.GONE);//申请中，不能评价
                    ivHolder.tvHint.setVisibility(View.VISIBLE);
                    ivHolder.tvHint.setText("审核中");
                }else if (itemtype.equals("2")) {
                    ivHolder.tvCommit.setVisibility(View.GONE);
                    ivHolder.tvHint.setVisibility(View.VISIBLE);
                    ivHolder.tvHint.setText("待退货");
                }else if (itemtype.equals("3")) {//拒绝退款
                    ivHolder.tvHint.setVisibility(View.VISIBLE);
                    ivHolder.tvHint.setText("退款失败");
                }else if (itemtype.equals("4")) {
                    ivHolder.tvCommit.setVisibility(View.GONE);
                    ivHolder.tvHint.setVisibility(View.VISIBLE);
                    ivHolder.tvHint.setText("退货中");
                }else if (itemtype.equals("5")) {
                    ivHolder.tvCommit.setVisibility(View.GONE);
                    ivHolder.tvHint.setVisibility(View.VISIBLE);
                    ivHolder.tvHint.setText("退款成功");
                }else {
                    ivHolder.tvCommit.setVisibility(View.GONE);
                    ivHolder.tvHint.setVisibility(View.VISIBLE);
                    ivHolder.tvHint.setText("退货中");
                }
            }
        }else
            ivHolder.tvAfterSale.setVisibility(View.GONE);
        ivHolder.tvCommit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                commitGoods(child.getId());
            }
        });
        ivHolder.tvAfterSale.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                applyAfterSale(child, mOrder.getRecvdate());
            }
        });
        layoutGoods.addView(view);
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
            case ORDER_GET:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
            case ORDER_GET:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_GET:
                HemaArrayResult<Order> bResult = (HemaArrayResult<Order>) baseResult;
                mOrder = bResult.getObjects().get(0);
                //订单类型keytype：1:普通订单;2:定制订单;3:预约订单;4:代付订单
                if (mOrder.getKeytype().equals("2")) {//之前版本中，从通知消息中进入订单详情，预约、定制订单类型有错误，这里手动处理掉
                    Intent itCustom = new Intent(mContext, BuyerCustomOrderDetailActivity.class);
                    itCustom.putExtra("order_id", mOrder.getId());
                    startActivity(itCustom);
                    finish();
                }else if (mOrder.getKeytype().equals("3")) {
                    Intent it = new Intent(mContext, BookOrderDetailActivity.class);
                    it.putExtra("order_id", mOrder.getId());
                    startActivity(it);
                    finish();
                }else
                    setDatas();
                break;
            case ORDER_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if ("1".equals(keytype)) {
                    showTextDialog("取消成功");
                } else if ("2".equals(keytype)) {
                    showTextDialog("确定收货成功！");
                } else if ("7".equals(keytype)) {
                    showTextDialog("操作成功, 等待对方代付");
                }
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.UPDATE_ORDER);
                EventBus.getDefault().post(msg);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
                XtomToastUtil.showShortToast(mContext, "订单操作失败，"+baseResult.getMsg());
            case ORDER_GET:
                XtomToastUtil.showShortToast(mContext, "获取订单失败，"+baseResult.getMsg());
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
                XtomToastUtil.showShortToast(mContext, "订单操作失败");
                break;
            case ORDER_GET:
                XtomToastUtil.showShortToast(mContext, "获取订单失败");
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
        }
    }

    /**
     *
     * @param goods_id
     */
    public void commitGoods(String goods_id) {
        Intent itCommit = new Intent(mContext, CommentProductionActivity.class);
        itCommit.putExtra("goods_id", goods_id);
        startActivityForResult(itCommit, REQUEST_ORDER_COMMIT);
    }

    /**
     * 申请售后
     *
     * @param goods    订单中的商品
     * @param recvdate 订单的收货时间
     */
    public void applyAfterSale(BillChild goods, String recvdate) {
        Intent itCommit = new Intent(mContext, ApplyAfterSalesActivity.class);
        itCommit.putExtra("goods", goods);
        itCommit.putExtra("type", 1);
        itCommit.putExtra("recvdate", recvdate);//确认收货时间
        startActivityForResult(itCommit, REQUEST_ORDER_AFTERSALE);
    }
}
